package com.tengju.payment.infrastructure.schedule;

import com.tengju.bff.interfaces.covercharge.util.alarmUtil.MsgSendUtil;
import com.tengju.payment.application.transfer.TransferService;
import com.tengju.payment.domain.model.TradeStatus;
import com.tengju.payment.domain.model.transfer.Transfer;
import com.tengju.payment.domain.model.transfer.TransferRecordRepository;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class AutoTransferHandleJob {

    private final TransferService transferService;

    private final TransferRecordRepository transferRecordRepository;

    @Autowired
    public AutoTransferHandleJob(TransferService transferService,
                                 TransferRecordRepository transferRecordRepository) {
        this.transferService = transferService;
        this.transferRecordRepository = transferRecordRepository;
    }

    @XxlJob("autoTransferHandleJob")
    public ReturnT<String> execute(String params) {

        List<Transfer> createTransfers = transferRecordRepository.findByStatus(TradeStatus.PROCESS);

        if (CollectionUtils.isEmpty(createTransfers)) {
            return ReturnT.SUCCESS;
        }

        log.info("处理中的转账记录发起转账,总笔数:" + createTransfers.size());

        createTransfers.forEach(transfer -> {
            try {
                transferService.processTransferHandle(transfer);
            } catch (Exception e) {
                log.error("转账发起失败", e);
                MsgSendUtil.sendLarkMsg("转账记录查询失败,转账流水号{}", transfer.getBusinessNo());

            }
        });
        return ReturnT.SUCCESS;
    }
}
